package com.atguigu.tingshu.user.strategy.impl;

import cn.hutool.core.date.DateUtil;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.model.user.UserVipService;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.user.mapper.UserInfoMapper;
import com.atguigu.tingshu.user.mapper.UserVipServiceMapper;
import com.atguigu.tingshu.user.mapper.VipServiceConfigMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component("1003")
@Slf4j
public class VipStrategy implements ItemTypeStrategy {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private UserVipServiceMapper userVipServiceMapper;
    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;
    @Override
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //vip
        //判断是否已经新增过记录
        LambdaQueryWrapper<UserVipService> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(UserVipService::getOrderNo,userPaidRecordVo.getOrderNo());
        Long aLong = userVipServiceMapper.selectCount(lambdaQueryWrapper);
        if (aLong>0){
            return;
        }
        //添加vip服务购买记录
        UserVipService userVipService = new UserVipService();
        userVipService.setOrderNo(userPaidRecordVo.getOrderNo());
        userVipService.setUserId(userPaidRecordVo.getUserId());
        //查看用户信息
        UserInfo userInfo = userInfoMapper.selectById(userPaidRecordVo.getUserId());
        //获取会员到期时间
        Date vipExpireTime = userInfo.getVipExpireTime();
        Integer isVip = userInfo.getIsVip();
        //查看充值的会员类型
        VipServiceConfig vipServiceConfig = vipServiceConfigMapper.selectById(userPaidRecordVo.getItemIdList().get(0));
        //获取这个类型的月份
        Integer serviceMonth = vipServiceConfig.getServiceMonth();
        //判断是否还是会员
        if (isVip==1 && vipExpireTime.after(new Date()) ){
            //如果是会员,开始时间是原本的结束时间
            userVipService.setStartTime(vipExpireTime);
            //过期时间为原本到期时间加上服务月份
            userVipService.setExpireTime(DateUtil.offsetMonth(vipExpireTime, serviceMonth));
        }else {
            //不是会员开始时间为现在
            userVipService.setStartTime(new Date());
            //不是会员就是现在加上服务月份
            userVipService.setExpireTime(DateUtil.offsetMonth(new Date(), serviceMonth));
        }
        userVipServiceMapper.insert(userVipService);
        //更新用户会员状态
        userInfo.setIsVip(1);
        userInfo.setVipExpireTime(userVipService.getExpireTime());
        userInfo.setUpdateTime(new Date());
        userInfoMapper.updateById(userInfo);
    }
}
